<template>
    <view>
        <!-- pages/rooms/rooms.wxml -->
        <!-- 自定义导航栏 -->
        <custom-navbar :showTitle="true" backgroundColor="#ffffff" textColor="#ffffff" :showBack="false"
            :isCoverNav="false"></custom-navbar>
        <view class="roomContainer" :style="{height: contentHeight + 'px'}">
            <view class="roomContainer-swiper">
                <swiper class="swiper">
                    <swiper-item class="swiper-item">
                        <image src="https://image.shengxuankj.com/fronts/roomListBanner.png" mode="" />
                    </swiper-item>
                </swiper>
            </view>
            <view class="roomContainer-info">
                <view class="roomContainer-info-title">民宿故事</view>
                <view class="roomContainer-info-view">
                    <text class="tips">发现每一个角落的美好故事</text>
                </view>
            </view>

            <!-- 使用Pinterest瀑布流组件 -->
            <Pinterest :height="scrollHeight" :items="stories" :isLoading="isLoading" :hasMore="hasMore"
                @itemClick="handleStoryClick" @loadMore="loadMore" />
        </view>

        <!-- 悬浮球 -->
        <view class="floating-button" @tap="goToPublishStory">
            <view class="floating-icon">+</view>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { onShow } from '@dcloudio/uni-app'
    import { ref, onMounted, nextTick } from 'vue';
    import customNavbar from '../../components/custom-navbar/index.vue';
    import Pinterest from '../../components/Pinterest/index.vue';

    // 注册组件
    const components = {
        customNavbar,
        Pinterest
    };
    import { postListFun } from '@/api/port';
    // 类型定义
    interface Story {
        [key: string]: any;
    }

    interface TouchEvent {
        currentTarget: {
            dataset: {
                story: Story;
            };
        };
    }

    // 响应式数据
    const stories = ref<Story[]>([]);
    const navHeight = ref<number>(uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88);
    const navBarHeight = ref<number>(0);
    const tabBarHeight = ref<number>(0);
    const contentHeight = ref<number>(0);
    const scrollHeight = ref<number>(0);
    const isLoading = ref<boolean>(false);
    const hasMore = ref<boolean>(true);
    const totalPages = ref<number>(0);
    const currentPage = ref<number>(1);
    const systemInfo = ref<any>()



    /**
     * 计算主要内容区域的高度
     */
    const calculateContentHeight = async (): void => {
        const swiperHeight = ref(0);
        const infoHeight = ref(0);
        
        // 使用Promise包装DOM查询，确保同步执行
        const getSwiperHeight = () => {
            return new Promise((resolve) => {
                const roomContainerSwiper = uni.createSelectorQuery().select('.roomContainer-swiper');
                roomContainerSwiper.boundingClientRect((rect) => {
                    if (rect) {
                        swiperHeight.value = rect.height;
                        console.log('swiperHeight:', swiperHeight.value);
                    }
                    resolve(rect?.height || 0);
                }).exec();
            });
        };
        
        const getInfoHeight = () => {
            return new Promise((resolve) => {
                const roomContainerInfo = uni.createSelectorQuery().select('.roomContainer-info');
                roomContainerInfo.boundingClientRect((rect) => {
                    if (rect) {
                        infoHeight.value = rect.height;
                        console.log('infoHeight:', rect, infoHeight.value);
                    }
                    resolve(rect?.height || 0);
                }).exec();
            });
        };
        
        // 等待所有DOM查询完成后再执行后续计算
        await Promise.all([getSwiperHeight(), getInfoHeight()]);
        
        systemInfo.value = await uni.getWindowInfo();
        console.log(systemInfo)
        // 首页导航栏不占用空间，所以内容高度就是窗口高度减去tabbar高度
        const contentHeightValue = systemInfo.value.windowHeight;
        console.log(contentHeightValue, swiperHeight.value, infoHeight.value, navHeight.value)
        contentHeight.value = contentHeightValue - navHeight.value;
        scrollHeight.value = contentHeightValue - swiperHeight.value - infoHeight.value - navHeight.value;
    };

    // 跳转到故事详情
    const goToStoryDetail = (e: TouchEvent): void => {
        console.log(e)
        const story = e.currentTarget.dataset.story;
        uni.showToast({
            title: '查看故事：' + story.title,
            icon: 'none',
            duration: 2000
        });
        // 这里可以跳转到故事详情页面
        uni.navigateTo({
            url: '/subpackage/talesDetail/talesDetail?id=' + story.id,
        })
    };

    // 返回上一页
    const goBack = (): void => {
        uni.navigateBack();
    };

    // 跳转到发布故事页面
    const goToPublishStory = (): void => {
        uni.navigateTo({
            url: '/subpackage/publishStory/publishStory'
        });
    };
    /**
     * 分页参数
     */
    const pageParams = ref({
        page_no: 1,
        page_size: 10,
    })
    /**
     * 调用接口获取故事列表
     * @param {boolean} isLoadMore 是否为加载更多
     * @returns 
     */
    const getStoryList = async (isLoadMore: boolean = false) => {
        if (isLoading.value) return;

        isLoading.value = true;

        try {
            const res = await postListFun({
                page_no: pageParams.value.page_no,
                page_size: pageParams.value.page_size,
            });

            if (res.code === 1) {
                const newStories = res.data.list || [];
                totalPages.value = Math.ceil(res.data.total / pageParams.value.page_size) || 0;

                if (isLoadMore) {
                    // 加载更多，追加数据
                    stories.value = [...stories.value, ...newStories];
                } else {
                    // 首次加载，替换数据
                    stories.value = newStories;
                }

                // 检查是否还有更多数据
                hasMore.value = pageParams.value.page_no < totalPages.value;

                if (newStories.length > 0 && hasMore.value) {
                    pageParams.value.page_no++;
                }
            } else {
                uni.showToast({
                    title: res.msg || '获取数据失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        } catch (error) {
            console.error('获取故事列表失败:', error);
            uni.showToast({
                title: '网络错误，请重试',
                icon: 'none',
                duration: 2000
            });
        } finally {
            isLoading.value = false;
        }
    }

    const handleStoryClick = (e: TouchEvent) => {
        const story = e
        uni.showToast({
            title: '查看故事：' + story.title,
            icon: 'none',
            duration: 2000
        });
        // 这里可以跳转到故事详情页面
        uni.navigateTo({
            url: '/subpackage/talesDetail/talesDetail?id=' + story.id,
        })
    }

    /**
     * 上拉加载更多
     */
    const loadMore = async () => {
        if (isLoading.value || !hasMore.value) {
            return;
        }

        console.log('触发上拉加载，当前页:', pageParams.value.page_no);
        await getStoryList(true);
    }

    onShow(() => {
        getStoryList(false);
    })
    /**
     * 生命周期函数--监听页面加载
     */
    onMounted( async () => {
        await nextTick( async()=>{
            await getStoryList(false);
            // 计算剩余可视高度
            await calculateContentHeight();
        });

        // 获取故事列表数据
        
    });


</script>
<style>

    /* pages/rooms/rooms.wxss */
    .roomContainer {
        /* background-color: #f5f5f5; */
        height: 100vh;
    }

    .roomContainer-swiper {
        width: 100%;
    }

    .swiper {
        width: 100%;
        padding: 0 30rpx;
        box-sizing: border-box;
        height: 426rpx;
    }

    .swiper .swiper-item {
        width: 100%;
        height: 100%;
    }

    .swiper .swiper-item image {
        width: 100%;
        height: 100%;
        border-radius: 10rpx;
    }

    .roomContainer-info {
        width: 100%;
        padding: 30rpx;
        box-sizing: border-box;
        /* margin-top: 24rpx; */
        /* margin-bottom: 20rpx; */
    }

    .roomContainer-info .roomContainer-info-title {
        /** 文本1 */
        font-size: 36rpx;
        font-weight: bold;
        letter-spacing: 0px;
        line-height: 52.13rpx;
        color: rgba(19, 19, 19, 1);
    }

    .roomContainer-info .roomContainer-info-view {
        width: 100%;
        display: flex;
        align-items: baseline;
        justify-content: flex-start;
        margin-top: 12rpx;
    }

    .roomContainer-info .roomContainer-info-view .status {
        width: 88rpx;
        height: 35rpx;
        /** 文本1 */
        font-size: 24rpx;
        font-weight: 400;
        letter-spacing: 0px;
        /* line-height: 34.75rpx; */
        color: rgba(82, 145, 70, 1);
        background: rgba(188, 237, 185, 0.3);
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid rgba(82, 145, 70, 1);
        border-radius: 5rpx;
    }

    .roomContainer-info .roomContainer-info-view .tips {
        /** 文本1 */
        font-size: 24rpx;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 34.75rpx;
        color: rgba(153, 153, 153, 1);
        margin-left: 12rpx;
    }

    .roomContainer-info-view .site {
        width: calc(100% - 68rpx);
        height: 40rpx;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        padding: 0 8rpx;
        box-sizing: border-box;
        border-radius: 5rpx;
        background-color: rgba(245, 247, 245, 1);
    }

    .roomContainer-info-view .site .site-icon {
        width: 32rpx;
        height: 32rpx;
    }

    .roomContainer-info-view .site text {
        /** 文本1 */
        font-size: 24rpx;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 34.75rpx;
        color: rgba(102, 102, 102, 1);
        margin-left: 12rpx;
    }

    .roomContainer-info-view .telIcon {
        width: 40rpx;
        height: 40rpx;
        margin-left: 30rpx;
    }

    /* .tabClass { */
    /* } */



    /* 悬浮球样式 */
    .floating-button {
        position: fixed;
        right: 30rpx;
        bottom: 120rpx;
        width: 100rpx;
        height: 100rpx;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
        z-index: 999;
        transition: all 0.3s ease;
    }

    .floating-button:active {
        transform: scale(0.95);
        box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
    }

    .floating-icon {
        font-size: 48rpx;
        color: white;
        font-weight: 300;
        line-height: 1;
    }

    /* 加载状态样式 */
    .loading-status {
        width: 100%;
        padding: 40rpx 0;
        text-align: center;
    }

    .loading-text,
    .no-more-text,
    .empty-text {
        font-size: 28rpx;
        color: #999;
        line-height: 1.5;
    }

    .loading-text {
        color: #666;
    }

    .empty-text {
        color: #ccc;
        padding: 80rpx 0;
    }
</style>
